package com.hdoit.ares.web.acti.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.RedEnvelopeRecord;
import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IRedEnvelopeRecordService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.acti.model.ActiReward;
import com.hdoit.ares.logical.acti.model.Activity;
import com.hdoit.ares.logical.acti.service.IActiRewardService;
import com.hdoit.ares.logical.acti.service.IActivityService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.cust.service.ISendMsgService;
import com.hdoit.ares.logical.share.model.ViewTime;
import com.hdoit.ares.logical.share.service.IViewTimeService;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeRecordType;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeStatusType;
import com.hdoit.ares.selfcommon.enums.ser.GoodsCurrencyState;
import com.hdoit.ares.selfcommon.utils.DateBetween;
import com.hdoit.ares.selfcommon.utils.MathRewardUtil;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.logical.file.model.OssFileInfo;
import com.tennetcn.common.logical.file.service.IOssFileInfoService;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.component.webapi.BaseApi;
import com.tennetcn.component.webapi.ResponseModel;
import com.tennetcn.component.webapi.ResponseStatus;
import com.tennetcn.web.cbase.ApiAuthPassport;

@Controller
@RequestMapping(value = "/api/v1/activityAres/", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json;charset=utf-8")
@Api(value = "/api/v1/activityAres/")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ActivityAresApi extends BaseApi {

	private IOssFileInfoService fileInfoService;

	public IOssFileInfoService getFileInfoService() {
		return fileInfoService;
	}
	@Resource
	public void setFileInfoService(IOssFileInfoService fileInfoService) {
		this.fileInfoService = fileInfoService;
	}

	private IActivityService activityService;

	public IActivityService getActivityService() {
		return activityService;
	}

	@Resource
	public void setActivityService(IActivityService activityService) {
		this.activityService = activityService;
	}

	private IViewTimeService viewTimeService;

	public IViewTimeService getViewTimeService() {
		return viewTimeService;
	}

	@Resource
	public void setViewTimeService(IViewTimeService viewTimeService) {
		this.viewTimeService = viewTimeService;
	}

	private IActiRewardService actiRewardService;

	public IActiRewardService getActiRewardService() {
		return actiRewardService;
	}

	@Resource
	public void setActiRewardService(IActiRewardService actiRewardService) {
		this.actiRewardService = actiRewardService;
	}

	private ICustomerService customerService;

	public ICustomerService getCustomerService() {
		return customerService;
	}

	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	private IWithdrawParamService withdrawParamService;

	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}

	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}

	private ISendMsgService sendMsgService;

	public ISendMsgService getSendMsgService() {
		return sendMsgService;
	}

	@Resource
	public void setSendMsgService(ISendMsgService sendMsgService) {
		this.sendMsgService = sendMsgService;
	}

	private IRedEnvelopeRecordService redEnvelopeRecordService;

	public IRedEnvelopeRecordService getRedEnvelopeRecordService() {
		return redEnvelopeRecordService;
	}

	@Resource
	public void setRedEnvelopeRecordService(IRedEnvelopeRecordService redEnvelopeRecordService) {
		this.redEnvelopeRecordService = redEnvelopeRecordService;
	}

	private IAccountInfoService accountInfoService;

	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}

	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}

	private final String hotActivityApi = "hotActivity";
	private final String localActivityApi = "localActivity";
	private final String activityInfoApi = "activityInfo";
	private final String taskApi = "task";
	private final String activity001Api = "activity001";
	private final String choujiangApi = "choujiang";
	private final String toRewardApi = "toReward";

	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = hotActivityApi)
	@ApiOperation(notes = hotActivityApi, httpMethod = "POST", value = "热门活动列表")
	public String hotActivityList() {

		ResponseModel rm = new ResponseModel();

		/* 真实的图片路径前缀 */
		String preUrl = "http://putiyoli-1254043822.cosgz.myqcloud.com";

//		/* 测试的图片路径前缀 */
//		String preUrl = "http://test-1254043822.cosgz.myqcloud.com";

		// 获取所有热门资讯
		List<Activity> hotActivitys = activityService.queryListHotActivitys();
		if (hotActivitys.size() > 0) {
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("ok");
			for (Activity hotActivity : hotActivitys) {
				if (!StringUtils.isEmpty(hotActivity.getActiImg())) {
					OssFileInfo ossFileInfo = fileInfoService.queryModel(hotActivity.getActiImg());
					hotActivity.setActiImg(preUrl + ossFileInfo.getFilename());

					Date startDate = hotActivity.getStartDate();
					Date endDate = hotActivity.getEndDate();

					String leftDate = DateBetween.leftDate(DateUtils.getCurrent(), startDate, endDate);
					if ("0".equals(leftDate)) {
						hotActivity.setDateBetween("0");
					} else {
						String[] signs = leftDate.split("_");
						String sign = signs[0];
						String date = signs[1];
						hotActivity.setSigns(sign);
						hotActivity.setDateBetween(date);
						ViewTime viewTime = viewTimeService.queryModelByShareId(hotActivity.getId(), "activity");
						hotActivity.setViewTime(viewTime);
					}
					String actiId = hotActivity.getId();
					String reward = actiRewardService.querySumReward(actiId);
					String actiReward = hotActivity.getReward();
					double actiRewardDouble = Double.valueOf(actiReward);
					if (!StringUtils.isEmpty(reward)) {
						if (!StringUtils.isEmpty(actiReward)) {
							double rewardDouble = Double.valueOf(reward);
							double leastReward = actiRewardDouble - rewardDouble - 200;
							hotActivity.setLeastReward(leastReward);
						}
					} else if (StringUtils.isEmpty(reward)) {
						hotActivity.setLeastReward(actiRewardDouble);
					}
				}
			}
		} else {
			rm.setMessage("没有查询到数据");
		}
		rm.put("hotActivitys", hotActivitys);
		return rm.toJson();
	}

	@ResponseBody
	@RequestMapping(value = localActivityApi)
	@ApiOperation(notes = localActivityApi, httpMethod = "POST", value = " 本地活动列表")
	public String localActivity() {

		ResponseModel rm = new ResponseModel();

		return rm.toJson();
	}

	@ResponseBody
	@RequestMapping(value = activityInfoApi)
	@ApiOperation(notes = activityInfoApi, httpMethod = "POST", value = " 活动咨询列表")
	public String activityInfo() {

		ResponseModel rm = new ResponseModel();

		return rm.toJson();
	}

	@ResponseBody
	@RequestMapping(value = taskApi)
	@ApiOperation(notes = taskApi, httpMethod = "POST", value = " 任务列表")
	public String task() {

		ResponseModel rm = new ResponseModel();

		return rm.toJson();
	}

	@ResponseBody
	@RequestMapping(value = activity001Api)
	@ApiOperation(notes = activity001Api, httpMethod = "POST", value = "活动1详情列表")
	public String activity001(@ApiParam("活动主键") @RequestParam(value = "id", required = true) String id) {

		ResponseModel rm = new ResponseModel();

		// 更新参加活动次数
		viewTimeService.updateViewTimeById(id, "activity");

		/* 真实的图片路径前缀 */
		/* String preUrl = "http://putiyoli-1254043822.cosgz.myqcloud.com"; */

		/* 测试的图片路径前缀 */
		String preUrl = "http://test-1254043822.cosgz.myqcloud.com";

		// 查询当前活动详情
		Activity activity = activityService.queryModel(id);
		if (!StringUtils.isEmpty(activity.getActiImg())) {
			OssFileInfo ossFileInfo = fileInfoService.queryModel(activity.getActiImg());
			activity.setActiImg(preUrl + ossFileInfo.getFilename());

			// 判断当前活动的状态
			Date startDate = activity.getStartDate();
			Date endDate = activity.getEndDate();
			String leftDate = DateBetween.leftDate(DateUtils.getCurrent(), startDate, endDate);
			if ("0".equals(leftDate)) {
				activity.setDateBetween("0");
			} else {
				String[] signs = leftDate.split("_");
				String sign = signs[0];
				String date = signs[1];
				activity.setSigns(sign);
				activity.setDateBetween(date);
			}
			rm.put("activity", activity);

			// 查询当前活动参与次数
			ViewTime viewTime = viewTimeService.queryModelByShareId(activity.getId(), "activity");
			rm.put("viewTime", viewTime);

			// 查询当前活动的中奖名单
			List<ActiReward> actiRewards = actiRewardService.queryList(id);
			rm.put("actiRewards", actiRewards);

			// 查询当前用户的等级
			String custId = getLoginId();
			Customer customer = customerService.queryModel(custId);
			String level = customer.getLevel();
			rm.put("level", level);

			// 判断当前用户加入初创的时间
			Date joinMarkDate = customer.getJoinMakerDate();
			String joinDate = DateUtils.dateFormat(joinMarkDate);

			if (!StringUtils.isEmpty(joinDate)) {
				String joinDateBetween = DateBetween.dateBetween(joinMarkDate, startDate, endDate);
				rm.put("joinDateBetween", joinDateBetween);
			}
		} else {
			rm.setMessage("没有查询到数据");
		}

		return rm.toJson();
	}

	@ResponseBody
	@RequestMapping(value = choujiangApi)
	@ApiOperation(notes = choujiangApi, httpMethod = "POST", value = "抽奖界面")
	public String choujiang(@ApiParam("活动主键") @RequestParam(value = "actiId", required = true) String actiId) {

		ResponseModel rm = new ResponseModel();

		String customerId = getLoginId();
		Customer customer = customerService.queryModel(customerId);

		ActiReward actiReward = actiRewardService.queryModelByCustId(customerId);
		Integer mathRewardUtil = MathRewardUtil.main();
		if (!StringUtils.isEmpty(actiReward)) {
			System.err.println("actiReward not empty");
			mathRewardUtil = 0;
			System.err.println("actiReward is  empty");
			return activity001(actiId);
		}
		rm.put("mathRewardUtil", mathRewardUtil);

		Activity activity = activityService.queryModel(actiId);
		Date startDate = activity.getStartDate();
		Date endDate = activity.getEndDate();

		Date joinMakerDate = customer.getJoinMakerDate();
		if (joinMakerDate != null) {
			System.err.println("joinMakerDate ！= null");
			String makerDate = DateBetween.dateBetween(joinMakerDate, startDate, endDate);
			if (!"between".equals(makerDate) || ("between".equals(makerDate) && !StringUtils.isEmpty(actiReward))) {
				System.err.println("between ！= makerDate");
				return activity001(actiId);
			}
		} else {
			System.err.println("joinMakerDate == null");
			return activity001(actiId);
		}
		Date joinHighMakerDate = customer.getJoinHighMakerDate();
		if (joinHighMakerDate != null) {
			System.err.println("joinHighMakerDate == null");
			String highMakerDate = DateBetween.dateBetween(joinHighMakerDate, startDate, endDate);
			if (!"between".equals(highMakerDate) || ("between".equals(highMakerDate) && !StringUtils.isEmpty(actiReward))) {
				System.err.println("between == highMakerDate");
				return activity001(actiId);
			}
		}
		rm.put("actiId", actiId);

		// 将获奖名单传到前台
		List<ActiReward> actiRewards = actiRewardService.queryList();
		rm.put("actiRewards", actiRewards);

		return rm.toJson();
	}

	@ResponseBody
	@RequestMapping(value = toRewardApi)
	@ApiOperation(notes = toRewardApi, httpMethod = "POST", value = "更新活动奖金列表")
	public String toReward(@ApiParam("活动主键") @RequestParam(value = "actiId", required = true) String actiId) {
		ResponseModel rm = new ResponseModel();

		System.err.println("toReward actiId" + actiId);
		// 查询是否抽过奖
		String customerId = getLoginId();
		System.err.println("customerId" + customerId);
		Customer customer = customerService.queryModel(customerId);
		String id = "empty";
		ActiReward actiReward = actiRewardService.queryModelByCustId(customerId);
		Integer mathRewardUtil1 = MathRewardUtil.main();
		if (!StringUtils.isEmpty(actiReward)) {
			mathRewardUtil1 = 0;
		} else {
			actiReward = new ActiReward();
			actiReward.setId(CommonUtils.getKeyId());
			actiReward.setActiId(actiId);
			actiReward.setCustomerId(customer.getId());
			actiReward.setRewardDate(DateUtils.getCurrent());
			String userName = customer.getUsername();
			if (!StringUtils.isEmpty(userName)) {
				actiReward.setUserName(userName);
			} else {
				throw new RuntimeException("error:someOne filing reward");
			}
			actiReward.setRewardCurrency(GoodsCurrencyState.yuan);

			if (mathRewardUtil1 == 1) {
				WithdrawParam withdrawParam = withdrawParamService.queryModelByHelpCode("thirdReward");
				actiReward.setReward(String.valueOf(withdrawParam.getParam()));
			} else if (mathRewardUtil1 == 3) {
				WithdrawParam withdrawParam = withdrawParamService.queryModelByHelpCode("firstReward");
				actiReward.setReward(String.valueOf(withdrawParam.getParam()));
			} else if (mathRewardUtil1 == 6) {
				WithdrawParam withdrawParam = withdrawParamService.queryModelByHelpCode("secondReward");
				actiReward.setReward(String.valueOf(withdrawParam.getParam()));
			} else {
				return activity001(actiId);
			}

			actiReward.setDeleteMark("1");
			actiReward.setModelStatus(ModelStatus.add);
			if (!actiRewardService.applyChange(actiReward)) {

				throw new RuntimeException("actiReward save error");
			}

			RedEnvelopeRecord redEnvelopeRecord = new RedEnvelopeRecord();
			String redEnvelopeRecordId = CommonUtils.getKeyId();
			redEnvelopeRecord.setId(redEnvelopeRecordId);
			redEnvelopeRecord.setReceiverId(customerId);
			String refereeId = customer.getRefereeId();
			if (!StringUtils.isEmpty(refereeId)) {
				redEnvelopeRecord.setRefreeId(refereeId);
				Customer refreeCustomer = customerService.queryModel(refereeId);
				redEnvelopeRecord.setRefreeLevel(refreeCustomer.getLevel());
			}
			redEnvelopeRecord.setJoinId(customer.getId());
			redEnvelopeRecord.setJoinLevel(customer.getLevel());
			redEnvelopeRecord.setRedMoney(Double.valueOf(actiReward.getReward()));
			redEnvelopeRecord.setSendDate(DateUtils.getCurrent());
			redEnvelopeRecord.setCategory(RedEnvelopeRecordType.joinByrefreeCustomer);
			redEnvelopeRecord.setRedenvelopeStatus(RedEnvelopeStatusType.notReceived);
			redEnvelopeRecord.setTradeNo("");
			redEnvelopeRecord.setDuration(RedEnvelopeStatusType.duration);
			redEnvelopeRecord.setModelStatus(ModelStatus.add);

			// 如果红包记录添加成功
			if (redEnvelopeRecordService.applyChange(redEnvelopeRecord)) {
				id = redEnvelopeRecordId;
			}
		}
		String mathRewardUtil = String.valueOf(mathRewardUtil1);
		System.err.println("mathRewardUtil" + mathRewardUtil);
		System.err.println("id" + id);

		rm.put("id", id);
		rm.put("mathRewardUtil", mathRewardUtil);

		return rm.toJson();
	}
}
